package prueba.PrimefacesSVN.persistencia;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class UsuariosAbstract {
	protected String UNIDAD_DE_PERSISTENCIA = "PrimefacesSVN";
	protected EntityManagerFactory factory;
	protected EntityManager em;

	public UsuariosAbstract() {
		factory = Persistence
				.createEntityManagerFactory(UNIDAD_DE_PERSISTENCIA);
		em = factory.createEntityManager();
	}

	protected void anadir(Object obj) {
		try {
			em.persist(obj);
			em.flush();
			em.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			em.getTransaction().rollback();
		}
	}

	protected List consultarNameQuery(String namedQuery) {
		List lista = null;
		try {
			EntityTransaction entr = em.getTransaction();
			if (!entr.isActive()) {
				entr.begin();
			}
			Query query = em.createNamedQuery(namedQuery);
			lista = query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lista;
	}

	protected Object compruebaExistencia(String query, String param) {
		Object obj=null;
		try {
			EntityTransaction entr = em.getTransaction();
			if (!entr.isActive()) {
				entr.begin();
			}
			Query aux = em.createQuery(query);
			aux.setParameter("login", param);
			obj = aux.getSingleResult();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
}
